<?php
/** require:
 *  __PHY_LIB
 */
require_once(__PHY_LIB . "/class/Item.class.php");

class HelpArticle extends Item {
/// definition and constructor ///
	function HelpArticle($id=0, $field="") {
		Query::Query();
		$this->cfgKeyField("id");
		$this->cfgAllField("id,category_id,title,rank,content,time_updated");
		$this->cfgTable("cms_help_article");
		if ("" == $field || "*" == $field) {
			$this->cfgField($this->mAllField);
		}
		else {
			$this->cfgField($field);
		}
		if (0 < $id) {
			$this->cfgWhere($this->mKeyField . "=" . $id);
			$this->load();
		}
		else {
			$this->set($this->mKeyField, $id);
		}
	}

	function invalid() {
		if (!$this->get('title')) {
			return 'title';
		}

		return false;
	}

	function calcNewRank() {
		$sQ = "SELECT MAX(rank) max_rank FROM cms_help_article WHERE category_id='".(int)$this->get('category_id')."'";
		$this->loadQuery($sQ);
		$r = $this->nextRecord(false);
		return (int)$r['max_rank'] + 1;
	}

	function rankTo($nRank) {
		if (!(0 < $this->getID())) { return false; }
		$nRank = max(1, (int)$nRank);
		if ($nRank > $this->get('rank')) { // 增大
			$oList = new HelpArticleList();
			$oList->cfgWhere("category_id='".$this->get('category_id')."' AND rank>'".$this->get('rank')."' AND rank<='{$nRank}'");
			$oList->load();
			while ($o = $oList->nextItem()) {
				$o->set('rank', $o->get('rank') - 1); // 中间的统统-1
				$o->update();
			}
		}
		elseif ($nRank < $this->get('rank')) { // 减小
			$oList = new HelpArticleList();
			$oList->cfgWhere("category_id='".$this->get('category_id')."' AND rank<'".$this->get('rank')."' AND rank>='{$nRank}'");
			$oList->load();
			while ($o = $oList->nextItem()) {
				$o->set('rank', $o->get('rank') + 1); // 中间的统统+1
				$o->update();
			}
		}
		else { // 相等，没变动
			return true;
		}
		/// 修改自己 ///
		$this->set('rank', $nRank);
		$this->update();
		return true;
	}

} /// end class HelpArticle.


class HelpArticleList extends ItemList {
	/// definition and constructor ///
	function HelpArticleList($tablename=null) {
		ItemList::ItemList();
		$this->cfgClass("HelpArticle");
		$this->cfgKeyField("id");
		$this->cfgAllField("id,category_id,title,rank,content,time_updated");
		$this->cfgTable(null == $tablename ? "cms_help_article" : $tablename);
	}

} /// end class HelpArticleList.
?>
